import os
from flask import Blueprint, request, render_template, jsonify, current_app

from applications.common.utils.http import fail_api, success_api, table_api
from applications.common.utils.rights import authorize
from applications.extensions import db
from applications.models import Photo
from applications.common.utils import upload as upload_curd
import zipfile

bp = Blueprint('adminKyc', __name__, url_prefix='/kyc')


@bp.get('/')
@authorize("system:kyc:main")
def index():
    return render_template('system/kyc/index.html')


@bp.get('/table')
@authorize("system:kyc:main")
def table():
    page = request.args.get('page', type=int)
    limit = request.args.get('limit', type=int)
    data, count = upload_curd.get_zip(page=page, limit=limit)
    return table_api(data=data, count=count)


#   上传
@bp.get('/upload')
# @authorize("system:kyc:add", log=True)
def upload():
    return render_template('system/kyc/upload.html')


#   上传接口
@bp.post('/upload')
# @authorize("system:kyc:add", log=True)
def upload_api():
    if 'file' in request.files:
        photo = request.files['file']
        mime = request.files['file'].content_type

        file_url = upload_curd.upload_zip(photo=photo, mime=mime)
        res = {
            "msg": "上传成功",
            "code": 0,
            "success": True,
            "data":
                {"src": file_url}
        }
        return jsonify(res)
    return fail_api()


@bp.post('/unzip')
def unzip():
    _id = request.form.get('id')
    photo = upload_curd.get_by_id(_id)
    file_dir = 'D:/python/pear-admin-flask/static/upload/' + photo.name
    unzip_dir = 'D:/python/pear-admin-flask/static/unzip/' + photo.name
    if zipfile.is_zipfile(file_dir):
        with zipfile.ZipFile(file_dir, 'r') as zip_ref:
            zip_ref.extractall(unzip_dir)
        res = {
            "msg": "解压成功",
            "code": 0,
            "success": True,
            "data": 'ok'
        }
        return jsonify(res)
    else:
        return fail_api('不是zip文件')
